import base64
import requests
from PIL import Image
import io
import json

def encode_image_to_base64(image_path):
    """
    读取图片并将其编码为 Base64 格式
    """
    with open(image_path, "rb") as img_file:
        # 读取图片并转化为 Base64 字符串
        return base64.b64encode(img_file.read()).decode("utf-8")

def send_request_to_fastapi(base64_image):
    """
    发送 POST 请求到 FastAPI 服务
    """
    # url = "http://127.0.0.1:8048/detect_image/"
    url = "http://127.0.0.1:8048/detect_image/"
    headers = {"Content-Type": "application/json"}
    data = {
        "base64_image": base64_image
    }

    # 发送请求并获取响应
    response = requests.post(url, json=data, headers=headers)

    # 打印响应结果
    if response.status_code == 200:
        # print("Response:", response.json())
        formatted_response = json.dumps(response.json(), indent=4, ensure_ascii=False)
        print("Response:", formatted_response)
    else:
        print(f"Request failed with status code {response.status_code}")

if __name__ == "__main__":
    image_path = "test3.jpg"  # 替换为你的图片路径
    base64_image = encode_image_to_base64(image_path)  # 将图片编码为 Base64
    send_request_to_fastapi(base64_image)  # 发送请求到 FastAPI 服务
